package com.xkdx.guangguang.fragment.shopinfo;

import java.io.File;
import java.util.HashMap;

import org.apache.http.entity.mime.content.FileBody;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.EditerUpload;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.user.UserRegistModule.DetailInfo;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.User;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class PhotoEditFragment extends BaseFragment implements OnClickListener {
	View view;
	Button back, upload;
	ImageView upload_image_choice;
	EditText title, info_detail;
	TextView start_time, end_time;
	Spinner info_type;
	AlertDialog.Builder builder;
	Dialog dialog;
	View datepick;
	DatePicker dp;
	String start_time_str, end_time_str;
	String editImagePath;
	boolean isStartTime = true;
	boolean isNew = true;
	User user;
	DetailInfo info;
	String shopID;
	ProgressDialog pd;
	String infoType = "1";
	int[] ms = { R.string.new_product_info, R.string.stores_preferential };
	String[] Type = { "1", "2" };
	EditeAction editeAction;
	EditeModule editeModule;
	EditePresistence editePresistence;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		shopID = getArguments().getString("shopID");
		pd = new ProgressDialog(getActivity());
		pd.setMessage("正在上传。。。");

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.upload_new_cheap, container, false);
		findView();
		setOnClick();
		return view;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.upload_image:
			Intent intent = new Intent(getActivity(), EditerUpload.class);
			startActivity(intent);
			break;
		case R.id.start_time:
			isStartTime = true;
			dialog.show();
			break;
		case R.id.end_time:
			isStartTime = false;
			dialog.show();
			break;
		case R.id.upload_new_cheap_back:
			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			break;
		case R.id.photo_update:
			showLoading();
			break;
		default:
			break;
		}

	}

	private void setDialog() {
		builder = new AlertDialog.Builder(getActivity());
		datepick = LayoutInflater.from(getActivity()).inflate(R.layout.update_user_info_datapicker, null);
		dp = (DatePicker) datepick.findViewById(R.id.datePicker1);
		builder.setView(datepick);
		builder.setTitle("选择日期");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (isStartTime) {
					dialog.cancel();
					start_time_str = dp.getYear() + "-" + (dp.getMonth() + 1) + "-" + dp.getDayOfMonth();
					start_time.setText(start_time_str);
				} else {
					dialog.cancel();
					end_time_str = dp.getYear() + "-" + (dp.getMonth() + 1) + "-" + dp.getDayOfMonth();
					end_time.setText(end_time_str);
				}

			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		dialog = builder.create();

	}

	BaseAdapter ba = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(R.layout.editer_upload_spinner_item, null);
			}
			TextView tv = (TextView) convertView.findViewById(R.id.editer_upload_spinner_item);
			tv.setText(getString(ms[position]));

			return convertView;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 2;
		}
	};

	@Override
	public void findView() {
		back = (Button) view.findViewById(R.id.upload_new_cheap_back);
		upload = (Button) view.findViewById(R.id.photo_update);
		upload_image_choice = (ImageView) view.findViewById(R.id.upload_image);
		info_type = (Spinner) view.findViewById(R.id.info_type);
		start_time = (TextView) view.findViewById(R.id.start_time);
		end_time = (TextView) view.findViewById(R.id.end_time);
		title = (EditText) view.findViewById(R.id.title);
		info_detail = (EditText) view.findViewById(R.id.info_detail);
		setDialog();

	}

	@Override
	public void setOnClick() {

		upload_image_choice.setOnClickListener(this);
		info_type.setAdapter(ba);
		info_type.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				infoType = Type[position];
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		start_time.setOnClickListener(this);
		end_time.setOnClickListener(this);
		back.setOnClickListener(this);
		upload.setOnClickListener(this);

	}

	// 上传图片
	@Override
	public void showLoading() {
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		editeAction = new EditeAction(su.getUserID(), shopID, su.getUserLoginToken(), infoType, title.getText()
				.toString(), start_time_str, end_time_str, info_detail.getText().toString());
		if (EditerUpload.isNative) {
			editeAction.editeCutFileBody = new FileBody(setFile(EditerUpload.editUri));
		}
		editeModule = new EditeModule();
		editePresistence = new EditePresistence(this);
		((ManagerActivity) getActivity()).addCurrentTask(editePresistence);
		editePresistence.setActitons(editeAction);
		editePresistence.setModule(editeModule);
		editePresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (editePresistence != null) {
					editePresistence.cancel(true);
				}
				getFragmentManager().popBackStack();
			}
		});
		dataLoadDialog.show();

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			if (editeModule.isEditeSuccess) {
				Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
				getFragmentManager().popBackStack();
			} else {
				Toast.makeText(getActivity(), editeModule.message, Toast.LENGTH_SHORT).show();
			}
		} else {
			showErrorTip(map);
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onResume() {
		if (EditerUpload.editeUploadBitmap != null) {
			upload_image_choice.setImageBitmap(EditerUpload.editeUploadBitmap);
		}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		if (EditerUpload.editeUploadBitmap != null) {
			EditerUpload.editeUploadBitmap.recycle();
			EditerUpload.editeUploadBitmap = null;
		}
		super.onDestroy();
	}

	private File setFile(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = getActivity().managedQuery(uri, proj, null, null, null);
		int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		String img_path = actualimagecursor.getString(actual_image_column_index);
		// Log.i(TAG, img_path);
		return new File(img_path);

	}
}
